//
//  ReviewsHeaderView.m
//  JiaoX
//
//  Created by yinqy on 15/1/6.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//

#import "ReviewsHeaderView.h"
#import "ProdCateHViewCell.h"
#import "LeftLineView.h"
#import "ProductItemInfo.h"
#import "ProdPromotion.h"
#import "JXProdDetailCtl.h"
#import "JXReviewsController.h"
#import "HomeDataTool.h"
#import "JXBaseResponse.h"
#import "AnimUtils.h"

#define TITLE_FONT_SIZE [DimensUtils getScaleX:16]
#define PRAISE_FONT_SIZE 12

@interface ReviewsHeaderView()<UIWebViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate>
{
    LeftLineView *_titleView;
    
    UIWebView *_webView;
    //点赞的Btn
    UIButton *_praiseBtn;
    UIButton *_readNumBtn;
    UILabel *_fromLabel;
    //装有查看此货的btn和商品的collectview
    
    UIButton *_goBtn;
    UICollectionView *_collectView;
    
    NSArray *_prodArray;
    
    Reviews *_reviews;
    //猜你喜欢
    LeftLineView *_likeView;
    //评论
    LeftLineView *_comtView;
    
    BOOL havaData;
}
@end

@implementation ReviewsHeaderView

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self!=nil){
        [self setBackgroundColor:JXGlobalColorBg];
        // 1.添加标题
        
        _titleView = [[LeftLineView alloc]initWithTitleFontSize:TITLE_FONT_SIZE];
        _titleView.x = JXPublicInset;
        _titleView.y = JXPublicInset*2;
        [_titleView.label setTextColor:[UIColor blackColor]];
        [self addSubview:_titleView];
        
        // 2.添加webview
        _webView = [[UIWebView alloc]init];
        [_webView setDelegate:self];
        [_webView setUserInteractionEnabled:NO];
        [_webView setFrame:CGRectMake(0, CGRectGetMaxY(_titleView.frame)+JXPublicInset*2, JXScreenW, 300)];
        [self addSubview:_webView];
        
        // 3.添加点赞
        _praiseBtn = [[UIButton alloc]init];
        UIImage * unPraiseImage = [UIImage imageNamed:@"icon_unpraise"];
        [_praiseBtn setImage:unPraiseImage forState:UIControlStateNormal];
        
        [_praiseBtn.titleLabel setFont:[UIFont systemFontOfSize:PRAISE_FONT_SIZE]];
        [_praiseBtn setTitleColor:JXColor(153, 153, 153) forState:UIControlStateNormal];
        [_praiseBtn setTitleColor:JXThemeColor forState:UIControlStateDisabled];
        
        UIImage * praiseImage = [UIImage imageNamed:@"icon_praise"];
        [_praiseBtn setImage:praiseImage forState:UIControlStateDisabled];
        
        [_praiseBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
        [_praiseBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0)];
        [_praiseBtn setTitle:@"0" forState:UIControlStateNormal];
        [_praiseBtn setFrame:CGRectMake(JXPublicInset, CGRectGetMaxY(_webView.frame)+JXPublicInset*2, 30, praiseImage.size.height)];
        [self addSubview:_praiseBtn];
        
        // 4.添加阅读数
        _readNumBtn = [[UIButton alloc]init];
        UIImage * readNumImage = [UIImage imageNamed:@"readNum_icon"];
        [_readNumBtn setImage:readNumImage forState:UIControlStateNormal];
        [_readNumBtn.titleLabel setFont:[UIFont systemFontOfSize:PRAISE_FONT_SIZE]];
        [_readNumBtn setTitleColor:JXColor(153, 153, 153) forState:UIControlStateNormal];
        [_readNumBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
        [_readNumBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0)];
        [_readNumBtn setTitle:@"0" forState:UIControlStateNormal];
        [_readNumBtn setFrame:CGRectMake(JXScreenW/2-15, _praiseBtn.y, _praiseBtn.width, _praiseBtn.height)];
        [self addSubview:_readNumBtn];
        
        // 5.添加来源
        _fromLabel = [[UILabel alloc]init];
        [_fromLabel setFont:[UIFont systemFontOfSize:PRAISE_FONT_SIZE]];
        [_fromLabel setTextColor:JXColor(153, 153, 153)];
        [_fromLabel setSize:CGSizeMake(0, PRAISE_FONT_SIZE)];
        [_fromLabel setY:_readNumBtn.y];
        [self addSubview:_fromLabel];
        
        // 6.1 添加大按钮
        _goBtn = [[UIButton alloc]init];
        [_goBtn setTitle:@"抢先体验这货" forState:UIControlStateNormal];
        [_goBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [_goBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_goBtn setContentMode:UIViewContentModeCenter];
        [_goBtn setBackgroundImage:[UIImage resizedImage:@"btn_login_bg"] forState:UIControlStateNormal];
        [self addSubview:_goBtn];
        
        // 6.2 添加猜你喜欢
        _likeView = [[LeftLineView alloc]initWithTitleFontSize:TITLE_FONT_SIZE];
        _likeView.hidden = YES;
        [_likeView setText:@"猜你喜欢" constrainedToSize:CGSizeMake(JXScreenW-JXPublicInset*2, MAXFLOAT)];
        [self addSubview:_likeView];
        
        // 6.3 添加collectionview
        UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayout alloc]init];
        UICollectionView *collectView  =[[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:flowLayout];
        collectView.backgroundColor = JXGlobalColorBg;
        [collectView registerClass:[ProdCateHViewCell class] forCellWithReuseIdentifier:PROD_IDENTIFIER];
        _collectView = collectView;
        [self addSubview:collectView];
        
        
        // 7 添加评论的标签
        _comtView = [[LeftLineView alloc]initWithTitleFontSize:TITLE_FONT_SIZE];
        [_comtView setText:@"评论" constrainedToSize:CGSizeMake(JXScreenW-JXPublicInset*2, MAXFLOAT)];
        _comtView.hidden = YES;
        [self addSubview:_comtView];
        [self addKVO];
        
        [self setFrame:CGRectMake(0, 0, JXScreenW, CGRectGetMaxY(_readNumBtn.frame)+20)];
    }
    return self;
}
/**
 *  添加webview的内容改变监听
 */
-(void)addKVO{
    UIScrollView *scrollview = [[_webView subviews]firstObject];
    [scrollview addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if([keyPath isEqualToString:@"contentSize"])
    {
        NSValue *oldSize = [change objectForKey:@"old"];
        NSValue *newSize = [change objectForKey:@"new"];
        if ([oldSize CGSizeValue].height!=[newSize CGSizeValue].height) {
            [self webViewDidFinishLoad:_webView];
        }
    }
}

-(void)setTitle:(NSString *)title{
    [_titleView setText:title constrainedToSize:CGSizeMake(JXScreenW-JXPublicInset*2, MAXFLOAT)];
}

- (void)setReviewsData:(Reviews *)reviews prodList:(NSArray *)prodList{
    havaData = YES;
    _reviews = reviews;
    _prodArray = [NSMutableArray arrayWithArray:prodList];
    //将商品的赠品设置成空。
    [_prodArray makeObjectsPerformSelector:@selector(setProdPromotion:) withObject:nil];
    
    [self setTitle:reviews.postName];
    
    [_webView loadHTMLString:reviews.content baseURL:nil];
    [_webView setY:CGRectGetMaxY(_titleView.frame)+JXPublicInset*2];
    
    NSString *praiseNum = [NSString stringWithFormat:@"%d",reviews.praiseNum];
    [_praiseBtn setTitle:praiseNum forState:UIControlStateNormal];
    [_praiseBtn setWidth:[praiseNum sizeWithFont:[UIFont systemFontOfSize:PRAISE_FONT_SIZE]].width+_praiseBtn.imageView.image.size.width+5];
    
    NSString *readNum = [NSString stringWithFormat:@"%d",reviews.readNum];
    [_readNumBtn setTitle:readNum forState:UIControlStateNormal];
    [_readNumBtn setWidth:[readNum sizeWithFont:[UIFont systemFontOfSize:PRAISE_FONT_SIZE]].width+_readNumBtn.imageView.image.size.width+5];
    [_fromLabel setText:reviews.resource];
    [_fromLabel setWidth:[reviews.resource sizeWithFont:[UIFont systemFontOfSize:PRAISE_FONT_SIZE]].width];
    [_fromLabel setX:JXScreenW-JXPublicInset-_fromLabel.width];
    
    if (reviews.isPraise==1) {
        //改变状态
        [_praiseBtn setEnabled:NO];
    }else{
        [_praiseBtn addTarget:self action:@selector(praiseReviews) forControlEvents:UIControlEventTouchUpInside];
    }
}

/**
 *  点赞
 */
-(void)praiseReviews{
    MBProgressHUD *HUD = [DialogUtils showLoadingWithView:((UIViewController *)self.delegate).navigationController.view];
    [HomeDataTool doPraiseWithReviewsId:self.reviewsId success:^(JXBaseResponse *result) {
        [HUD hide:YES];
        if ([Utils isBlankString:result.data]) {
            //点赞成功，需要加上点赞动画
            [_praiseBtn setEnabled:NO];
            [AnimUtils praiseAnim:_praiseBtn];
        }else{
            [DialogUtils showTipsWithView:((UIViewController *)self.delegate).navigationController.view String:result.data];
        }
    } failure:^(NSError *error) {
        [HUD hide:YES];
        [DialogUtils showTipsWithView:((UIViewController *)self.delegate).navigationController.view String:@
         "操作失败"];
    }];
}

-(void)webViewDidFinishLoad:(UIWebView *)webView{
    
    CGSize actualSize = [webView sizeThatFits:CGSizeZero];
    
    CGRect newFrame = webView.frame;
    newFrame.size.height = actualSize.height;
    webView.frame = newFrame;
    
    _praiseBtn.y = CGRectGetMaxY(_webView.frame)+JXPublicInset;
    _readNumBtn.y = _praiseBtn.y;
    _readNumBtn.x = CGRectGetMaxX(_praiseBtn.frame)+JXPublicInset*2;
    
    _fromLabel.y = _readNumBtn.y;
    _fromLabel.x = JXScreenW-_fromLabel.width-JXPublicInset;
    
    CGFloat comtViewY =  CGRectGetMaxY(_fromLabel.frame)+JXPublicInset*3;
    
    if(![Utils isBlankString:_reviews.url]){
        //如果url不为空，那么
        [_goBtn setFrame:CGRectMake(JXPublicInset, CGRectGetMaxY(_fromLabel.frame)+JXPublicInset, JXScreenW-JXPublicInset*2, 46.5)];
        [_goBtn addTarget:self action:@selector(goBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        comtViewY = CGRectGetMaxY(_goBtn.frame)+JXPublicInset*3;
    }
    
    if(_prodArray!=nil &&_prodArray.count>0){
        _collectView.delegate = self;
        _collectView.dataSource=self;
        
        CGFloat likeViewY = CGRectGetMaxY(_fromLabel.frame)+JXPublicInset*4;
        if (![Utils isBlankString:_reviews.url]) {
            likeViewY = CGRectGetMaxY(_goBtn.frame)+JXPublicInset*2;
        }
        [_likeView setFrame:CGRectMake(JXPublicInset, likeViewY, JXScreenW-2*JXPublicInset, [_likeView.label.font lineHeight])];
        _likeView.hidden = NO;
        CGFloat height = ((int)(_prodArray.count+1)/2)*(PRODCATEHVIEW_SMALL_HEIGHT+JXPublicInset)+JXPublicInset;
        [_collectView setFrame:CGRectMake(0, CGRectGetMaxY(_likeView.frame), JXScreenW,height )];
        
        comtViewY = CGRectGetMaxY(_collectView.frame)+JXPublicInset*3;
    }
    [_comtView setFrame:CGRectMake(JXPublicInset,comtViewY, JXScreenW-2*JXPublicInset, TITLE_FONT_SIZE)];
    _comtView.hidden = NO;
    
    self.frame = CGRectMake(0, 0, JXScreenW, CGRectGetMaxY(_comtView.frame));
    
    if ([self.delegate respondsToSelector:@selector(webviewLoadFinish)]) {
        [_delegate webviewLoadFinish];
    }
}

-(void)goBtnClick:(UIButton *)btn{
    if ([self.delegate respondsToSelector:@selector(goBtnClick)]) {
        [_delegate goBtnClick];
    }
}

#pragma Mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return _prodArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ProdCateHViewCell *cell = [ProdCateHViewCell cellWithTableView:collectionView indexPath:indexPath];
    [cell setProdData:_prodArray[indexPath.row] isAdd:false];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat width = (JXScreenW-3*JXPublicInset)*0.5;
    return CGSizeMake(width, PRODCATEHVIEW_SMALL_HEIGHT);
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    ProductItemInfo *itemInfo = _prodArray[indexPath.row];
    JXProdDetailCtl *proddc = [[JXProdDetailCtl alloc]initWithPordId:[NSString stringWithFormat:@"%d",itemInfo.prodId]];
    //这儿强转有点不太合理。先就这样
    [((JXReviewsController *)self.delegate).navigationController pushViewController:proddc animated:YES];
}

-(BOOL)haveData{
    return havaData;
}

-(void)dealloc{
    // 移除观察者
    UIScrollView *scrollview = [[_webView subviews]firstObject];
    [scrollview removeObserver:self forKeyPath:@"contentSize"];
}

@end
